<template>
    <el-drawer
        v-model="showDrawer"
        :title="drawerTitle"
        direction="rtl"
        @close="closeFn"
        :size="423"
        :close-on-click-modal="false"
    >
       <div class="">
           <el-form
                ref="formRef"
                :model="form"
                label-width="90px"
                :rules="rules"
            >
                <el-form-item label="产品名称:" prop="produceId">
                    <el-select  
                        @change="changeProduce" 
                        v-model="form.produceId"  
                        placeholder="请选择产品" 
                        :disabled="isEdit"
                        style="width: 100%;" size="small">
                        <el-option 
                            v-for="item in produceList"
                            :key="item.id"
                            :label="item.produceName"
                            :value="item.id"                           
                        ></el-option>
                    </el-select>
                    <!-- <el-input size="small" placeholder="请填写产品名称"  v-model="form.produceName"></el-input> -->
                </el-form-item>
                <el-form-item label="产品编码:" >
                    <el-input size="small" placeholder="请填写产品编码" :disabled="true"  v-model="form.produceCode"></el-input>
                </el-form-item>
                <el-form-item label="计划数量:" prop="planQuantity" >
                    <el-input-number @change.="changePlanNum" :controls="false"  style="width: 100%;"  size="small" placeholder="请填写计划数量"  v-model="form.planQuantity" />
                </el-form-item>
                <el-form-item label="生产时间:" prop="productTime" >
                    <!-- <el-input size="small" placeholder="请填写产品规格"  v-model="form.produceSpecs"></el-input> -->
                    <el-date-picker  
                        v-model="form.productTime"
                        type="date" size="small" 
                        style="width: 100%;"  
                        value-format="YYYY-MM-DD"                        
                        placeholder="请选择生产时间">
                    </el-date-picker>
                </el-form-item>
                <div>
                    <el-table :data="materialTableList" border size="small">
                        <el-table-column type="index" label="#" align="center" />   
                        <el-table-column prop="materialName" align="center" label="物料名称"></el-table-column>
                        <el-table-column prop="planQuantity" align="center" label="数量"></el-table-column>   
                    </el-table>
                </div>
           </el-form>
       </div>
       <div class="drawer-footer-box">
           <el-button size="small" @click="closeFn">取消</el-button>
           <el-button type="primary" size="small" :loading="isLoading" @click="submitInfo">确定</el-button>
        </div>
    </el-drawer>
</template>
<script>
import {onMounted, reactive, ref, toRefs} from 'vue'
import { ElMessage } from 'element-plus'

import axios from 'axios'
export default {
    name: 'productDrawer',
    props: {
       showDrawer: {
           type: Boolean,
           default: false,
           required: false
       },
       drawerTitle: {
           type: String,
           default: '新增',
           required: false
       }       
    },
    emits: ['closeDrawerFn','submitCallback'],
    setup(props, {emit}){
        let data  = reactive({
          form: {
              produceId: '',
              produceCode: '',
              produceName: '',
              produceSpecs: '',
              planQuantity: 1,
              productTime: '',
              produceType: ''
          },
          produceList: [],
          materialTableList: [],
          produceId: 1,
          isLoading: false,
          isEdit: false
        })
        const rules = reactive({
            produceCode: [
                {
                    required: true,
                    message: '请填写产品编码！',
                    trigger: 'change',
                },
            ],
            produceId: [
                {
                    required: true,
                    message: '请填写产品名称！',
                    trigger: 'change',
                },
            ],
            planQuantity: [
                {
                    required: true,
                    message: '请填写计划数量！',
                    trigger: 'change',
                }
            ],
            productTime: [
                {
                    required: true,
                    message: '请选择生产时间！',
                    trigger: 'change',
                }
            ],
        })        
        const formRef = ref(null)       
        function afterShowDrawer(rowData){     
            setTimeout(()=>{
                if(JSON.stringify(rowData)!== '{}'){
                     data.form = Object.assign({}, rowData)                       
                     data.materialTableList = []      
                     data.materialTableList = rowData.materailList     
                }    
                else{
                    data.form = {
                        produceId: '',
                        produceCode: '',
                        produceName: '',
                        produceSpecs: '',
                        planQuantity: 1,
                        productTime: '',
                        produceType: ''
                    }
                    data.materialTableList = []      
                }
                formRef.value.resetFields()       
            },400)                  
        }
        function closeFn(){
            data.isLoading = false     
            formRef.value.resetFields()       
            emit('closeDrawerFn')
        }
        async function addInfo(){
            let requstData = {}
            if(!data.isEdit){
                requstData = {
                    ...data.form, 
                    isEdit:data.isEdit, 
                    materialList: data.materialTableList,
                    purchaseCode: 'CG'+ new Date().getFullYear()+ (new Date().getMonth()+1)+new Date().getDate()
    ,               status: 0,
                }
            }
            else{
                requstData = {
                    ...data.form, 
                    isEdit:data.isEdit,                                         
                }
            }
            console.log('requstData',requstData)           
            // return
            let res = await axios.post('/addPurchaseInfo', requstData)
            let result = res.data
            if(result.success){
                ElMessage({
                    message: result.result,
                    type: 'success',
                })
                closeFn()
                emit('submitCallback')
            }
            else{
                ElMessage({
                    message: result.result,
                    type: 'error',
                })
                data.isLoading = false     
            }
        }
        function submitInfo(){
            // data.isLoading = true
            // console.log('formRef.value', formRef.value)
            // console.log('data.form,', data.form)
            formRef.value.validate((valid) => {
                if (valid) {
                    // console.log('data.form,', data.form)
                    // closeFn()
                    if(data.materialTableList.length===0){
                        ElMessage({
                            message: '产品未配置物料，请先配置物料！',
                            type: 'warning',
                        })
                    }
                    else{
                        addInfo()
                    }
                } else {                    
                    data.isLoading = false
                    return false
                }
            })            
            // console.log(data.isLoading)
            // console.log('提交数据')
        }
        function changeProduce(val){            
            let index = data.produceList.findIndex((item)=>{
                return item.id === val
            })   
            // console.log(data.produceList[index])        
            data.form.produceCode = data.produceList[index].produceCode      
            data.form.produceName = data.produceList[index].produceName            
            // console.log(data.form)
            data.produceId = val
            loadData()    
        }
        async function getProduceList(){
            let res = await axios.get('/productInfoList')
            let list = res.data
            if(list.success){
                data.produceList = []
                data.produceList = list.result.list               
            }        
           
        }
        async function loadData(){
            let result = await axios.get('/produceBomList',{
                params: { produceId: data.produceId}
            })
            let materialList = result.data
            if(materialList.success){
                data.materialTableList = []
                data.materialTableList = materialList.result
            }
            else{
                data.materialTableList = []
            }        
            data.materialTableList.forEach(item=>{
                // console.log('parseInt(item.materialUseNum)',parseInt(item.materialUseNum))                
                item.planQuantity = parseInt(item.materialUseNum) * parseInt(data.form.planQuantity)
                item.materialStatus = 0
            })                        
        }
        function changePlanNum(val){            
            if(data.materialTableList.length>0){                
                data.materialTableList.forEach(item=>{
                    item.planQuantity = parseInt(item.materialUseNum)*parseInt(val)                    
                })
            }
        }
        onMounted(()=>{
            getProduceList()             
        })
        return {
            rules,
            formRef,
            ...toRefs(data),          
            afterShowDrawer,  
            closeFn,
            submitInfo,
            changeProduce,
            getProduceList,
            changePlanNum,
            addInfo
        }    
    }
}
</script>
<style>
    .el-input-number .el-input__inner{
        text-align: left;
    }
</style>